package com.baizhi.administrator.service.impl;

import com.baizhi.administrator.dao.AdminMapper;
import com.baizhi.administrator.service.IAdminService;
import com.baizhi.common.exception.IllUsernameOrPwdException;
import com.baizhi.model.entity.Admin;
import com.baizhi.util.JwtUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gange
 * @since 2023-07-17
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Override
    public String login(Admin admin) {

        //用md5算法对密码再次加密
        String pwd = DigestUtils.md5DigestAsHex(admin.getPassword().getBytes(StandardCharsets.UTF_8));
//        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
//        wrapper.eq("username",admin.getUsername()).eq("password",pwd);
//        admin = baseMapper.selectOne(wrapper);

        admin = query().eq("username",admin.getUsername()).eq("password",pwd).one();

        if(admin==null){
            throw new IllUsernameOrPwdException("账号密码错误！");
        }
        //生成jwt
        Map<String,String> map = new HashMap<>();
        map.put("id",admin.getId().toString());
        map.put("name",admin.getUsername());
        map.put("avatar",admin.getAvatar());
        String jwt = JwtUtils.getToken(map);
        return jwt;
    }
}
